package rbac

import (
	"bytes"
	"context"
	"fmt"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/ecomp-analyzer-services/consts"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/dao"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/model"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/model/entity"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/service"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/exception"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/json"
	"time"
)

// AddAdminInvite 添加管理员邀请记录
func (r *sRbac) AddAdminInvite(ctx context.Context, in model.AdminInviteAddInput) (out *model.AdminInviteAddOutput, err error) {
	// 授权管理员
	admAuth := service.User().GetAdminUser(ctx)
	item := entity.AdminInvite{
		AdminId:       admAuth.Id,
		ManageName:    admAuth.ManageName,
		IsSuperManage: uint(in.IsSuperManage),
		Expired:       gtime.New(r.GetInviteExpired(ctx)),
	}
	if len(in.DepartId) > 0 {
		item.DepartId = gjson.MustEncodeString(in.DepartId)
	}
	// 生成Token
	item.Token = utils.CreateToken(gjson.MustEncodeString(item))

	// 保存数据
	if err = r.InviteModel().Save(ctx, item); err != nil {
		return nil, err
	}
	return &model.AdminInviteAddOutput{
		Token: item.Token,
	}, nil
}

// GetInviteList 获取管理员邀请列表
func (r *sRbac) GetInviteList(ctx context.Context, in model.AdminInviteGetListInput) (out *model.AdminInviteGetListOutput, err error) {
	var (
		columns = dao.AdminInvite.Columns()
		where   = g.Map{}
	)
	// 状态
	if in.Status.Fmt() != "" {
		where[columns.Status] = in.Status
	}

	// 获取数据
	out = &model.AdminInviteGetListOutput{}
	err = r.InviteModel().ListAndTotal(ctx, model.CommonListAndTotalInput{
		CommonPaginationItem: in.CommonPaginationItem,
		Where:                where,
		Sort:                 fmt.Sprintf(`%s %s`, columns.Id, consts.SortDesc),
	}, &out.Rows, &out.Total)
	return
}

// GetInviteDetail 获取管理员邀请记录详情
func (r *sRbac) GetInviteDetail(ctx context.Context, id uint) (detail *model.AdminInviteDetailItem, err error) {
	detail = &model.AdminInviteDetailItem{}
	// 获取详情
	err = r.InviteModel().DetailPri(ctx, id, &detail)
	return nil, err
}

// RefreshInviteExpired 刷新邀请效期时间
func (r *sRbac) RefreshInviteExpired(ctx context.Context, id uint) error {
	// 更新数据
	if err := r.InviteModel().Update(
		ctx,
		g.Map{dao.AdminInvite.Columns().Id: id},
		g.Map{
			dao.AdminInvite.Columns().Expired:    r.GetInviteExpired(ctx),
			dao.AdminInvite.Columns().RefreshNum: gdb.Raw(dao.AdminInvite.Columns().RefreshNum + `+1`),
		},
	); err != nil {
		return exception.New(`刷新效期时间失败，请重试`)
	}
	return nil
}

// GetInviteExpired 获取邀请过期时间
func (r *sRbac) GetInviteExpired(ctx context.Context) string {
	// 获取邀请过期时间-单位天
	return time.Now().
		Add(consts.TimeDay * time.Duration(
			service.Config().MustGetVar(ctx, `admin_invite_expired`).Int64(),
		)).Format(time.DateTime)
}

// parseInviteDepartId 解析邀请部门ID
func (r *sRbac) parseInviteDepartId(departId string) []uint {
	if len(departId) == 0 {
		return nil
	}
	var (
		decoder = json.NewDecoder(bytes.NewBuffer([]byte(departId)))
		ids     []uint
	)
	// 解析JSON
	if err := decoder.Decode(&ids); err != nil {
		return nil
	}
	return ids
}
